package com.luo.bbs.front.webapi.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luo.bbs.front.webapi.mapper.CommentMapper;
import com.luo.bbs.front.webapi.mapper.QuestionMapper;
import com.luo.bbs.front.webapi.pojo.UserLoginPrincipal;
import com.example.bbs.front.service.ICommentService;
import com.luo.common.exception.BBSServiceException;
import com.luo.common.restful.ResponseCode;

import com.luo.pojo.comment.dto.CommentDTO;
import com.luo.pojo.comment.entity.Comment;
import com.luo.pojo.comment.vo.CommentVO;
import com.luo.pojo.question.entity.Question;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 文章评论表 服务实现类
 * </p>
 *
 * @author bin.cn
 * @since 2023-01-19
 */
@Service
@Slf4j
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private QuestionMapper questionMapper;

    @Transactional
    @Override
    public CommentVO postComment(CommentDTO commentDTO) {
        log.debug("接受的参数是:{}",commentDTO);
        if (commentDTO==null){
            throw new BBSServiceException(ResponseCode.NOT_ACCEPTABLE,"参数不能为空");
        }

        Comment comment = new Comment();
        BeanUtils.copyProperties(commentDTO,comment);

        Integer userId = getUserId();
        String userNickName = getUserNickName();
        if (userNickName == null || userId == null){
            throw new BBSServiceException(ResponseCode.UNAUTHORIZED,"用户未登录");
        }
        comment.setUserId(userId);
        comment.setNickname(userNickName);
        comment.setId(UUID.randomUUID().toString().substring(0,10));

        //通过Id查询帖子,为标题赋值，当用户发表第一条评论时，标题没有值，因此在这赋值
        Integer questionId = commentDTO.getQuestionId();
        Question question = questionMapper.selectById(questionId);
        comment.setQuestionTitle(question.getTitle());

        //如果是二级评论，要加一些赋值,可能回复一级评论也可能回复二级
        if (commentDTO.getParentCommentId()!=null && commentDTO.getParentCommentUserId()!=null){
            comment.setCommentLevel(2);
        }
        int row = commentMapper.insert(comment);
        if (row!=1){
            throw new BBSServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"系统错误，请重试！");
        }

        //发表评论，该帖子的评论数加1
        question.setCommentViews(question.getCommentViews()+1);
        row = questionMapper.updateById(question);
        if (row!=1){
            throw new BBSServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"系统错误，请重试！");
        }

        //返回新增的对象信息，可以实时更新
        CommentVO commentVO = new CommentVO();
        BeanUtils.copyProperties(comment,commentVO);
        return commentVO;
    }

    @Override
    public List<CommentVO> commentTree(Integer questionId) {
        List<CommentVO> treeVO = new ArrayList<>();

        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        commentQueryWrapper.eq("question_id",questionId)
                .eq("status",1)
                .eq("delete_status",1)
                .eq("comment_level",1).orderByDesc("gmt_create");
        //查出该帖子的所有一级评论
        List<Comment> comments = commentMapper.selectList(commentQueryWrapper);

        for (Comment comment : comments) {
            //转换为指定类型
            CommentVO commentVO = new CommentVO();
            BeanUtils.copyProperties(comment, commentVO);
            String avatar = commentMapper.getAvatar(comment.getUserId(), comment.getId());
            commentVO.setAvatar(avatar);
            commentVO.setInputShow(false);
            treeVO.add(commentVO);
        }
        for (CommentVO commentVO : treeVO) {
            //该一级评论下的所有二级评论
            String parentId = commentVO.getId();
            QueryWrapper<Comment> parentCommentId = new QueryWrapper<Comment>()
                    .eq("status",1)
                    .eq("delete_status",1)
                    .eq("parent_comment_id", parentId).orderByAsc("gmt_create");
            //转换为指定类型
            List<Comment> list = commentMapper.selectList(parentCommentId);
            List<CommentVO> secondList = new ArrayList<>();
            for (Comment sonComment : list) {
                CommentVO sonCommentVO = new CommentVO();
                BeanUtils.copyProperties(sonComment,sonCommentVO);
                sonCommentVO.setInputShow(false);
                //评论设置头像
                String avatar = commentMapper.getAvatar(sonComment.getUserId(),sonComment.getId());
                sonCommentVO.setAvatar(avatar);
                //二级评论评论数
                sonCommentVO.setCommentViews(commentMapper.selectCount(new QueryWrapper<Comment>().
                        eq("reply_comment_id",sonCommentVO.getId())));
                secondList.add(sonCommentVO);
            }
            commentVO.setChildren(secondList);

            //为一级评论的评论数赋值
            commentVO.setCommentViews(commentMapper.selectCount(new QueryWrapper<Comment>()
                    .eq("parent_comment_id",commentVO.getId())));
        }
        return treeVO;
    }

    @Override
    public Integer getCountByUser(Integer userId) {
        //判断用户是否存在，略
        //判断用户传过来的ID是否是当前用户
        log.debug("接收的参数是{}",userId);
        if (!userId.equals(getUserId())){
            throw new BBSServiceException(ResponseCode.FORBIDDEN,"用户身份异常！");
        }
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        Integer integer = commentMapper.selectCount(wrapper);
        return integer;
    }


    /**
     * 获取用户信息
     * @return
     */
    public UserLoginPrincipal getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserLoginPrincipal principal = (UserLoginPrincipal) authentication.getPrincipal();
        if (principal==null){
            throw new BBSServiceException(ResponseCode.UNAUTHORIZED,"未登录！");
        }
        return principal;
    }

    public Integer getUserId() {
        if (getUserInfo()==null){
            return null;
        }
        return getUserInfo().getId();
    }

    public String getUserNickName() {
        if (getUserInfo()==null){
            return null;
        }
        return getUserInfo().getNickname();
    }
}
